package cn.huapu.power.energy.service.impl;

import cn.huapu.power.energy.mapper.BaseMapper;
import cn.huapu.power.energy.service.BaseService;
import cn.huapu.power.energy.vo.Grid;
import cn.huapu.power.energy.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseServiceImpl<M extends BaseMapper<T,K>,T,K> implements BaseService<T,K> {
	@Autowired
	protected M mapper;
	
	@Override
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	public int insert(T t) {		
		return mapper.insert(t);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	public int update(T t) {		
		return mapper.update(t);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)
	public int remove(K id) {		
		return mapper.remove(id);
	}

	@Override
	@Transactional(readOnly = true)
	public T get(K id) {		
		return (T)mapper.get(id);
	}

	@Override
	@Transactional(readOnly = true)
	public List<T> queryList(T t) {		
		return mapper.list(t);
	}
	@Override
	@Transactional(readOnly = true)
	public Grid<T> queryListByPage(Page page, T t) {
		Grid<T> grid = new Grid<T>();
    	if(t == null){
    		return grid;
    	}
    	if(page != null) {
    		if(page.getLimit() > page.getTotalCount()) {
    			grid.setTotal(page.getTotalCount());
    			return grid;
    		}
    	}
    	List<T> list = mapper.listByPage(page, t);    	
        grid.setRows(list);
        grid.setTotal(page.getTotalCount());     
        return grid;
	}
	@Override
	@Transactional(readOnly = true)
	public List<T> queryListByIds(String ids) {
		if(!StringUtils.isEmpty(ids)) {
			return mapper.getByIds(ids);
		}
		return new ArrayList<T>(0);
	}

}
